<script setup>
import { onShow, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { ref, nextTick } from "vue";
import tabbarView from "../components/tabbar.vue";
import { useUserStore } from "../../stores/user";
import { earnCount, skip, productnumber, mine } from "@/services/user";
import { messagenumber } from "@/services/message";
import { goPage } from "@/utils/newpage";
import { userloginStore } from "@/stores/islogin.js";
import { formatPrice } from "@/utils/formatPrice";

// 图片资源
import icon1 from "@/static/my/icon-1.png";
import icon2 from "@/static/my/icon-2.png";
import icon3 from "@/static/my/icon-3.png";
import icon4 from "@/static/my/icon-4.png";
import icon5 from "@/static/my/icon-5.png";

import listicon1 from "@/static/my/icon-gm1.png";
import listicon2 from "@/static/my/icon-gm2.png";
import listicon3 from "@/static/my/icon-gm3.png";
import listicon4 from "@/static/my/icon-gm4.png";
import listicon5 from "@/static/my/icon-gm5.png";
import listicon6 from "@/static/my/icon-gm6.png";
import listicon7 from "@/static/my/icon-gm7.png";
import listicon8 from "@/static/my/icon-gm8.png";
import listicon9 from "@/static/my/collection-img.png";

const user = useUserStore();
const userlogin = userloginStore();
const userinfo = ref(null);
const numobj = ref({});

const shwoinfo = ref(false);
const uCodeRef = ref(null);
const balance = ref({});
console.log(uCodeRef);

const infomode = ref({
  phone: "",
  name: "",
  code: "",
});

async function minefun() {
  let res = await mine();
  balance.value = res.data;
}

const tips = ref("");
const value = ref("");

const codeChange = (text) => {
  tips.value = text;
};

const getCode = () => {
  console.log(uCodeRef.canGetCode);
  if (uCodeRef.value.canGetCode) {
    // 模拟向后端请求验证码
    uni.showLoading({
      title: "正在获取验证码",
    });
    setTimeout(() => {
      uni.hideLoading();
      // 这里此提示会被start()方法中的提示覆盖
      uni.$u.toast("验证码已发送");
      // 通知验证码组件内部开始倒计时
      uCodeRef.value.start();
    }, 2000);
  } else {
    uni.$u.toast("倒计时结束后再发送");
  }
};

//#ifdef H5

uni.hideTabBar();
//#endif
onShow(() => {
  earnCountfun();
  valuetabbar.value = 2;

  if (user.userInfo) {
    userlogin.setlogin(true);
    minefun();
    getuserInfogfun();
  } else {
    productnumberfun();
    messagenumberfun();
    userinfo.value = {
      name: user.userInfo.name,
      nickname: user.userInfo.nickname,
      phone: user.userInfo.phone,
      agency: user.userInfo.agency,
      is_shop: user.userInfo.is_shop,
      avatar: user.userInfo.avatar,
      promo_code: user.userInfo.promo_code ? user.userInfo.promo_code : "",
    };
    minefun();
  }
});
let loginModal = false;
const newPage = (item) => {
  if (!item.url && !userinfo.value) {
    if (!loginModal) {
      uni.removeStorageSync("userInfo");
      loginModal = true;
      // 弹窗告诉用户去登录
      uni.showModal({
        title: "温馨提示",
        content: "此时此刻需要您登录喔~",
        // showCancel: false,
        confirmText: "去登录",
        cancelText: "再逛会",
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: "/pages/login/login",
            });
          }
          if (res.cancel) {
            loginModal = false;
            return;
          } else {
            if (res.cancel) {
            }
          }
          loginModal = false;
        },
      });
    }
    return;
  }

  // #ifdef H5 || APP-PLUS
  if (!item.url && userinfo.value) {
    showPassword.value = true;
    return;
  }
  // #endif
  goPage(item.url);
};

const showPassword = ref(false);

async function getuserInfogfun() {
  // try {

  if (!uni.getStorageSync("Authorization")) {
    return;
  }
  let res;
  res = await user.getuserInfo();
  if (res.code == 200) {
    userlogin.setlogin(true);
  }

  productnumberfun();
  messagenumberfun();
  userinfo.value = {
    name: res.name,
    nickname: res.nickname,
    phone: res.phone,
    agency: res.agency,
    is_shop: res.is_shop,
    avatar: res.avatar,
    supplier: res.supplier,
    promo_code: user.userInfo.promo_code ? user.userInfo.promo_code : "",
  };
  // } catch (e) {
  //   uni.showToast({
  //     title: e.info,
  //     icon: "none",
  //   });
  // }
}
async function productnumberfun() {
  let res = await productnumber();
  if (res.code == 200) {
    numobj.value = res.data;
    orderlist.value[0].num = res.data.noPay ? res.data.noPay : "";
    orderlist.value[1].num = res.data.noPostage ? res.data.noPostage : "";
    orderlist.value[2].num = res.data.noComment ? res.data.noComment : "";
    orderlist.value[3].num = res.data.refund ? res.data.refund : "";
    orderlist.value[4].num = res.data.all ? "" : "";
  }
}

const taoll = ref(null);
const linkobj = ref(null);
const valuetabbar = ref(2);
const statusBarHeight = ref(0);
const menuButtonInfo = ref(null);

async function earnCountfun() {
  // let res = await earnCount();
  // taoll.value = res.data;
  // let reslink = await skip();
  // linkobj.value = reslink.data;
}

// 响应式数据
//兼容小程序
// #ifdef MP-WEIXIN
menuButtonInfo.value = uni.getMenuButtonBoundingClientRect();
// #endif

statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;

const no_num = ref(0);
async function messagenumberfun() {
  let res = await messagenumber();
  if (res.code == 200) {
    no_num.value = res.data.no_num;
  }
}

// 前往消息
const goMessageList = () => {
  uni.navigateTo({
    url: "/pages/message-list/Index",
  });
};

const orderlist = ref([
  {
    name: "待付款",
    icon: icon1,
    num: "",
    url: "/pages/order/orderlist/index?status=-1",
    offset: [8, 5],
  },
  {
    name: "待提货",
    icon: icon2,
    num: "",
    url: "/pages/order/orderlist/index?status=0",
    offset: [8, 5],
  },
  {
    name: "已完成",
    icon: icon3,
    num: "",
    url: "/pages/order/orderlist/index?status=2",
    offset: [8, 5],
  },
  // {
  //   name: "售后",
  //   icon: icon4,
  //   num: "",
  //   url: "/pages/order/orderlist/index?status=4",
  //   offset: [4, 5],
  // },
  {
    name: "全部订单",
    icon: icon5,
    num: "",
    url: "/pages/order/orderlist/index?status=-2",
    offset: [0, 0],
  },
]);
const list = ref([
  // {
  //   name: "地址管理",
  //   icon: listicon1,
  //   num: 0,
  //   url: "/pages/address/index",
  // },
  {
    name: "我的足迹",
    icon: listicon2,
    num: 0,
    url: "/pages/mine/myTracks",
  },
  {
    name: "协议查看",
    icon: listicon3,
    num: 0,
    url: "/pages/mine/userAgreement",
  },
  // {
  //   name: "云仓客服",
  //   icon: listicon4,
  //   num: 0,
  //   url: "",
  // },

  {
    name: "我的客户",
    icon: listicon6,
    num: 0,
    url: "/pages/client/Index",
  },
  {
    name: "申请代理",
    icon: listicon7,
    num: 0,
    url: "/pages/upgrade/identityform",
  },
  // {
  //   name: "问题解答",
  //   icon: listicon8,
  //   num: 0,
  //   url: "/pages/mine/questionAnswer",
  // },
  // {
  //   name: "我的收藏",
  //   icon: listicon9,
  //   num: 0,
  //   url: "/pages/collection/index",
  // },
]);
const goWork = () => {
  uni.navigateTo({
    url: "/pages/team/shopkeeper/work",
  });
};
const godlfun = () => {
  uni.navigateTo({
    url: "/pages/team/shopkeeper/regionalAgent",
  });
};
const goJLfun = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/rewardlistnew",
  });
};

const gohbfun = () => {
  uni.navigateTo({
    url: "/pages/poster/index",
  });
};

// 前往推广码
const goProCotionCode = () => {
  uni.navigateTo({
    url: "/pages/promotion-code/Index",
  });
};

const gosettimg = () => {
  uni.navigateTo({
    url: "/pages/mysetting/modify/index",
  });
};

// 去更改推荐人
const goReferee = () => {
  uni.navigateTo({
    url: "/pages/mine/modifySupplier",
  });
};

const copyfun = (e) => {
  uni.setClipboardData({
    data: e,
    success: function () {
      uni.showToast({
        title: "已复制到粘贴板",
        icon: "none",
      });
    },
    fail: function (e) {
      console.log(e.errMsg, "eeeee");
      uni.showToast({
        title: e.errMsg,
        icon: "none",
      });
    },
  });
};

const callPhone = (phoneNumber) => {
  // 判断手机是否支持拨打电话功能
  if (uni.canIUse("makePhoneCall")) {
    uni.makePhoneCall({
      phoneNumber: phoneNumber, // 电话号码
      success: function () {},
      // fail: function () {
      //   uni.showToast({
      //     title: "拨打电话失败",
      //     icon: "error",
      //   });
      // },
    });
  } else {
    uni.showToast({
      title: "你的设备不支持拨打电话功能",
      icon: "none",
    });
  }
};

const showcard = () => {
  uni.navigateTo({
    url: "/pages/mycard/cardinfo/index",
  });
};

const goygfun = () => {
  // uni.navigateTo({
  //   url: "/pages/servicereward/myreward/rewardyg",
  // });

  uni.navigateTo({
    url: "/pages/servicereward/myreward/rewardlistnew",
  });
};
const godetlist = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/rewardlist",
  });
};

const gobalance = () => {
  uni.navigateTo({
    url: "/pages/servicereward/myreward/balance",
  });
};
// #ifdef MP-WEIXIN

onShareAppMessage(() => {
  return {
    title: "膳友会",
    path: "/pages/my/index?referrer_id=" + userinfo.value.promo_code,
    imageUrl: "",
  };
});

// 朋友圈分享
onShareTimeline(() => {
  return {
    title: "膳友会",
    path: "/pages/my/index?referrer_id=" + userinfo.value.promo_code,
    imageUr: "",
  };
});
// #endif
</script>
<template>
  <!-- <up-skeleton :loading="true" :animate="false" avatar rows="2"></up-skeleton> -->
  <view class="my-content u-skeleton">
    <!-- #ifdef APP-PLUS || MP-WEIXIN -->
    <view class="mycontent-top-bc"></view>
    <!-- #endif -->
    <!-- #ifndef MP || APP-PLUS  -->
    <view
      class="mycontent-top-bc"
      :style="{ top: statusBarHeight + 'px' }"
    ></view>

    <!-- #endif -->

    <view class="my-top">
      <view class="my-top-info">
        <view class="my-top-arr">
          <image
            :src="
              userinfo && userinfo.avatar
                ? userinfo.avatar
                : '../../static/index/icom-tx.png'
            "
            mode="aspectFill"
          ></image>
        </view>

        <view class="my-top-nameorphone">
          <view class="my-top-name">
            <text v-if="userinfo && userinfo.nickname">{{
              userinfo.nickname
            }}</text>
            <text v-else>{{
              userinfo && userinfo.name ? userinfo.name : "--"
            }}</text>
            <image
              @click="goProCotionCode"
              src="../../static/index/home_code.png"
              mode="heightFix"
            ></image
          ></view>

          <view class="my-top-phone">
            <text>{{
              userinfo && userinfo.phone ? userinfo.phone : "--"
            }}</text>
            <view
              class="my-agency"
              v-if="userinfo && userinfo.agency && userinfo.agency.icon"
            ></view>
            <image
              :src="
                userinfo && userinfo.agency && userinfo.agency.icon
                  ? userinfo.agency.icon
                  : ''
              "
              mode="heightFix"
            />
          </view>
        </view>
      </view>
      <!-- @click="goProCotionCode" -->
      <view class="my-top-messg">
        <view class="my-massage-name">
          <view class="top-masage-k" @click="goMessageList">
            <uni-badge
              class="uni-badge-left-margin"
              :text="no_num"
              absolute="rightTop"
              size="small"
              :offset="[2, 3]"
            >
              <image src="../../static/my/me_message.png" mode="widthFix" />
            </uni-badge> </view
        ></view>

        <image
          @click="gosettimg"
          src="../../static/my/me_settings.png"
          mode="widthFix"
        ></image>
      </view>
    </view>

    <view class="user-order">
      <view
        class="user-order-item"
        v-for="(item, index) in orderlist"
        :key="index"
        @click="newPage(item)"
      >
        <uni-badge
          class="uni-badge-left-margin"
          :text="item.num"
          absolute="rightTop"
          size="small"
          :offset="item.offset"
        >
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view></uni-badge
        >
      </view>
    </view>

    <view class="user-order user-list-gn">
      <view
        class="user-order-item"
        v-for="(item, index) in list"
        :key="index"
        @click.stop="newPage(item)"
      >
        <!-- <image :src="item.icon" mode="widthFix" />
        <view class="user-order-name">{{ item.name }}</view> -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="kefu" v-if="item.name == '云仓客服' && userinfo">
          <button
            open-type="contact"
            bindcontact="handleContact"
            session-from="sessionFrom"
          >
            <image :src="item.icon" mode="widthFix" />
            <view class="user-order-name">{{ item.name }}</view>
          </button>
        </view>
        <view v-else>
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view>
        </view>
        <!-- #endif -->

        <!-- #ifdef H5 || APP-PLUS -->
        <view class="kefu" v-if="item.name == '云仓客服'">
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view>
        </view>
        <view v-else>
          <image :src="item.icon" mode="widthFix" />
          <view class="user-order-name">{{ item.name }}</view>
        </view>
        <!-- #endif -->
      </view>
    </view>

    <!-- 密码弹框 -->
    <view class="password_show">
      <u-popup
        :show="showPassword"
        mode="center"
        round="10"
        @close="showPassword = false"
      >
        <view class="password">
          <view class="popup-content-title">膳友会小程序</view>
          <view class="popup-content-img">
            <image
              src="https://m-cloud.yibaitao.com/ad/9247cf6c917db6c7e9ac6c14461b5b.jpg"
              mode="widthFix"
            />
          </view>
        </view>
      </u-popup>
    </view>

    <!-- <view
      class="user-ghs"
      v-if="userinfo && userinfo.agency && userinfo.agency.id == 101"
    >
      <image src="../../static/my/icon-user.png" mode="widthFix" />
      <text
        >我的供货商：{{ userinfo ? userinfo.supplier.nickname : "---" }}</text
      >
    </view> -->
    <!-- v-if="(userinfo && userinfo.is_shop == false) || !userinfo" -->
    <!-- <view class="user-haibaoorfapiao">
      <view class="user-haibaoorfapiao-item" @click="gohbfun">
        <image src="../../static/my/icon-haibao.png" mode="widthFix" />
        <text>快速生产海报</text>
      </view>
      <view class="user-haibaoorfapiao-item" @click="showcard">
        <image src="../../static/my/myid.png" mode="widthFix" />
        <text>我的名片</text>
      </view>
    </view> -->

    <view
      class="my-iofo-content"
      v-if="
        userinfo &&
        userinfo.agency &&
        userinfo.agency.level &&
        userinfo.agency.level > 0
      "
    >
      <view class="my-iofo-content-left">
        <view
          class="my-iofo-content-left-item"
          style="margin-bottom: 0"
          @click="godlfun"
        >
          <!-- <image src="../../static/my/icon-haibao.png" mode="widthFix" /> -->
          <up-icon name="coupon" color="#6f6f6f" size="60rpx"></up-icon>
          <text>我的代理</text>
        </view>
      </view>

      <!-- <view class="my-iofo-content-right" @click="goWork()">
        <image src="../../static/my/icon-word.png" mode="widthFix" />
        <view class="my-iofo-content-right-name">我的工作台</view>
      </view> -->
    </view>

    <view
      class="my-iofo-content"
      v-if="(userinfo && userinfo.is_shop == false) || !userinfo"
    >
      <view class="my-iofo-content-left">
        <view class="my-iofo-content-left-item" @click="gohbfun">
          <image src="../../static/my/icon-haibao.png" mode="widthFix" />
          <text>快速生产海报</text>
        </view>
      </view>

      <!-- <view class="my-iofo-content-right" @click="goWork()">
        <image src="../../static/my/icon-word.png" mode="widthFix" />
        <view class="my-iofo-content-right-name">我的工作台</view>
      </view> -->
    </view>

    <view class="user-haibaoorfapiao" v-if="userinfo && userinfo.is_shop">
      <view class="user-haibaoorfapiao-item" @click="gohbfun">
        <image src="../../static/my/icon-haibao.png" mode="widthFix" />
        <text>快速生产海报</text>
      </view>
      <!-- <view class="user-haibaoorfapiao-item">
        <image src="../../static/my/icon-fp.png" mode="widthFix" />
        <text>开具发票</text>
      </view> -->
      <!-- <view class="user-haibaoorfapiao-item" @click="showcard">
        <image src="../../static/my/myid.png" mode="widthFix" />
        <text>我的名片</text>
      </view> -->
      <view class="user-haibaoorfapiao-item" @click="goWork()">
        <image src="../../static/my/icon-word.png" mode="widthFix" />
        <text>我的工作台</text>
      </view>
    </view>

    <view class="work-banner" style="margin-top: 20rpx">
      <view class="foodr-list">
        <view class="list-index">
          <view class="list-index-left">我的收入</view>
          <view class="list-index-right" @click="godetlist"
            >余额变动明细
            <image
              src="@/static/team/shopkeeper/icon-gm11.png"
              mode="widthFix"
            ></image>
          </view>
        </view>
      </view>

      <u-line></u-line>
      <view class="work-middle">
        <view class="work-middle-left">
          <view class="middle-left-top">账户余额（元）</view>
          <view class="middle-left-footer"
            >￥{{ formatPrice(balance.balance || 0) }}</view
          >
        </view>
        <view class="work-middle-right">
          <!-- <view class="middle-right-bt" @click="gopayment">代付</view> -->
          <view class="middle-right-bt withdrawal" @click="gobalance"
            >提现</view
          >
        </view>
      </view>
      <u-line></u-line>

      <view class="work-banner-footer">
        <view class="work-footer-box">
          <view class="left-box">
            <view class="work-left-text">预估收入</view>
            <view class="work-middle-img">
              <uni-tooltip
                class="item"
                content="未出账的预估收益"
                placement="right"
              >
                <view class="item">
                  <u-icon name="question-circle"></u-icon
                ></view>
              </uni-tooltip>
            </view>
            <view class="work-money" @click="goygfun"
              >￥{{ formatPrice(balance.expected_reward || 0) }}</view
            >
          </view>
        </view>
        <view class="work-footer-box">
          <view class="left-box">
            <view class="work-left-text">提现中</view>
            <view class="work-money"
              >￥{{ formatPrice(balance.settle_balance || 0) }}</view
            >
          </view>
        </view>
      </view>
    </view>
    <!-- <view class="my-iofo-content">
      <view class="my-iofo-content-left">
        <view
          class="my-iofo-content-left-item"
          style="margin-bottom: 0"
          @click="goJLfun"
        >
          <up-icon name="rmb-circle" color="#6f6f6f" size="56rpx"></up-icon>
          <text>我的奖励</text>
        </view>
      </view>

    </view> -->

    <!-- <view
      class="my-info"
      v-if="userinfo && userinfo.agency && userinfo.agency.id != 101"
    >
      <view class="my-info-sf">
        <image src="../../static/my/icon-user1.png" mode="scaleToFill" />
        <text>我的供货商：</text>
        <text class="my-info-sf-right">{{
          userinfo ? userinfo.supplier.nickname : "---"
        }}</text>
      </view>
      <view class="my-info-sf">
        <image src="../../static/my/icon-ghs.png" mode="scaleToFill" />
        <text>供货商 ID：</text>
        <text class="my-info-sf-right">{{
          userinfo ? userinfo.supplier.id : "---"
        }}</text>
        <up-copy :content="userinfo ? userinfo.supplier.id : '---'">
          <view class="my-info-sf-click"> 复制 </view>
        </up-copy>
      </view>
      
    </view> -->
  </view>

  <!-- #ifdef MP-WEIXIN || WEB  -->
  <tabbarView :value="valuetabbar"></tabbarView>
  <!-- #endif -->

  <!-- #ifdef MP-WEIXIN -->

  <uni-popup ref="popup" :animation="true" :is-mask-click="false">
    <view class="popup_content">
      <view class="popup_title">
        {{ title }}
      </view>
      <view class="popup_desc">
        {{ desc1 }}
      </view>
      <view class="popup_urlTitle" @click="openPrivacyContract">
        {{ urlTitle }}
      </view>
      <view class="popup_desc">
        {{ desc2 }}
      </view>
      <view class="popup_cz">
        <button
          id="disagree-btn"
          type="default"
          class="weui-btn"
          @click="handleDisagree"
        >
          不同意
        </button>
        <button
          id="agree-btn"
          type="primary"
          open-type="agreePrivacyAuthorization"
          class="weui-btn"
          @agreeprivacyauthorization="handleAgree"
        >
          同意并继续
        </button>
      </view>
    </view>
  </uni-popup>
  <!-- #endif -->

  <!-- 个人信息弹框 -->
  <u-popup :show="shwoinfo" mode="bottom" round="10" @close="shwoinfo = false">
    <view class="password password2">
      <u-form
        labelPosition="left"
        :model="infomode"
        ref="form1"
        labelWidth="100rpx"
      >
        <u-form-item label="手机号" prop="name" borderBottom ref="item1">
          <u-input
            v-model="infomode.name"
            border="none"
            placeholder="请输入手机号"
          ></u-input>
        </u-form-item>
        <u-form-item label="姓名" prop="name" borderBottom ref="item1">
          <u-input
            v-model="infomode.name"
            border="none"
            placeholder="请输入真实姓名"
          ></u-input>
        </u-form-item>
        <u-form-item label="验证码" prop="code" borderBottom ref="item1">
          <!-- #ifndef APP-NVUE -->
          <u-input placeholder="请输入验证码" v-model="infomode.code">
            <!-- #endif -->
            <!-- #ifdef APP-NVUE -->
            <u-input placeholder="请输入验证码" v-model="infomode.code">
              <!-- #endif -->
              <template #suffix>
                <u-code
                  ref="uCodeRef"
                  @change="codeChange"
                  seconds="60"
                  changeText="X秒重新获取"
                ></u-code>
                <u-button
                  @tap="getCode"
                  :text="tips"
                  type="success"
                  size="mini"
                  color="#00ada9"
                ></u-button>
              </template>
              <!-- #ifndef APP-NVUE -->
            </u-input>
            <!-- #endif -->
            <!-- #ifdef APP-NVUE -->
          </u-input>
          <!-- #endif -->
        </u-form-item>
      </u-form>
    </view>
  </u-popup>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
